/*
============================================================================
 Name        : $(Basename)ServerSession.cpp
 Author      : $(Author)
 Version     :
 Copyright   : $(Copyright)
 Description : Client's interface to the server's services.
============================================================================
*/

#include <e32math.h>
#include "$(Basename)Server.h"
#include "$(Basename)ServerSession.h"

LOCAL_C TInt CreateServerProcess()
	{
	const TUidType serverUid(KNullUid, KNullUid, K$(Basename)ServerUid);

	RProcess server;
	TInt errno = server.Create(K$(Basename)ServerFileName, KNullDesC, serverUid);
	if(errno)
		{
		return errno;
		}

	server.Resume();
	server.Close();

	return KErrNone;
	}

LOCAL_C TInt StartServer()
	{
	TFindServer find(K$(Basename)ServerName);
	TFullName name;

	TInt errno = find.Next(name);
	if(!errno)
		{
		// Server already running
		return KErrNone;
		}

	RSemaphore semaphore;
	errno = semaphore.CreateGlobal(K$(Basename)ServerSemaphoreName, 0);
	if(errno)
		{
		return errno;
		}

	errno = CreateServerProcess();
	if(errno)
		{
		return errno;
		}

	semaphore.Wait();
	semaphore.Close();

	return KErrNone;
	}

EXPORT_C R$(Basename)ServerSession::R$(Basename)ServerSession() : RSessionBase(), iExampleTimeBuffer(NULL, 0, 0)
	{
	}

EXPORT_C TInt R$(Basename)ServerSession::Connect()
	{
	TInt errno = StartServer();
	if(!errno)
		{
		errno = CreateSession(K$(Basename)ServerName, Version(), KDefaultMessageSlots);
		}
	return errno;
	}

EXPORT_C TVersion R$(Basename)ServerSession::Version() const
	{
	return TVersion(K$(Basename)ServMajorVersionNumber,
		K$(Basename)ServMinorVersionNumber,
		K$(Basename)ServBuildVersionNumber);
	}

EXPORT_C void R$(Basename)ServerSession::RequestTime(TTime& aTime, TRequestStatus& aStatus)
	{
	iExampleTimeBuffer.Set(reinterpret_cast<TUint8*>(&aTime), sizeof(aTime), sizeof(aTime));
	TIpcArgs args(&iExampleTimeBuffer);
	SendReceive(E$(Basename)ServRequestTime, args, aStatus);
	}

EXPORT_C void R$(Basename)ServerSession::CancelRequestTime() const
	{
	SendReceive(E$(Basename)ServCancelRequestTime);
	}
